package com.example.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.UserDto;
import com.example.entity.Account1;
import com.example.event.AddIntegralEvent;
import com.example.mapper.Account1Mapper;
import com.example.service.Account1Service;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;

/**
 * Created by IntelliJ IDEA2021.3
 * @Author: Tenghw
 * @Date: 2022/09/26  19:42
 * @Description:
 */
@Slf4j
@Service
public class Account1ServiceImpl extends ServiceImpl<Account1Mapper, Account1> implements Account1Service, ApplicationEventPublisherAware {

    /**
     * 通过set方法注入applicationEventPublisher实例
     */
    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        log.warn("springboot启动时自动触发...setApplicationEventPublisher...");
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 通过属性注入account1Mapper实例
     */
    @Autowired
    Account1Mapper account1Mapper;

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAccount1(Account1 account1) {
        //新用户注册
        int insert = account1Mapper.insert(account1);
        if (0 == insert) {
            //如果有异常最好抛出去，不然事务不会生效（即事务不回滚了）
            //return false;
            throw new RuntimeException("新增用户失败！");
        }
        if (!StringUtils.isEmpty(account1.getName())) {
            QueryWrapper<Account1> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", account1.getName());
            //注册成功后的用户account1_one
            Account1 account1_one = account1Mapper.selectOne(queryWrapper);
            //新增500积分
            UserDto userDto = new UserDto();
            userDto.setUserId(account1_one.getId());
            userDto.setIntegral(500);
            //当前时间(毫秒)
            //long now = DateUtil.current();
            LocalDateTime now = LocalDateTime.now();
            log.warn("当前时间：{}，insert={}了条数据", now, insert);
            //发布赠送积分事件AddIntegralEvent
            applicationEventPublisher.publishEvent(new AddIntegralEvent(userDto));
        }
        return true;
    }

}
